package com.softserveinc.moviedbapp.broadcastreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.softserveinc.moviedbapp.application.MovieDBApplication;

import java.io.File;

/* receives messages when there's changes in network state */
public class SDCardMountedReceiver extends BroadcastReceiver {

	private Context mContext;
	private String TAG = SDCardMountedReceiver.class.getSimpleName();

	public SDCardMountedReceiver(final Context ctx) {
		mContext = ctx;
	}

	@Override
	public void onReceive(final Context context, final Intent intent) {

		Log.i(TAG, "Storage " + intent.getData());
		/* update current cache dir, because sd card state changed */
		setCurrentCacheDir();

	}

	public void setCurrentCacheDir() {
		// Find the dir to save cached images
		String sdState = android.os.Environment.getExternalStorageState();
		File cacheDir = null;
		if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
			File sdDir = android.os.Environment.getExternalStorageDirectory();
			cacheDir = new File(sdDir, "data/com.softservecom.moviedbapp/images");
			Log.d(TAG, "SD CARD CACHE " + cacheDir.getPath());
		} else {
			cacheDir = mContext.getCacheDir();
			Log.d(TAG, "INTERNAL CACHE " + cacheDir.getPath());
		}

		if (!cacheDir.exists()) {
			cacheDir.mkdirs();
		}
		((MovieDBApplication) mContext).getBitMapManager().setCacheDir(cacheDir);
	}
}
